package com.gxd.base.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * Redis工具类
 * @author yang
 * @date   2018年6月7日
 */
@Component
public final class JedisTool {

    private final static String HOST = "192.168.50.55";
//    private final static String HOST = "127.0.0.1";
    private final static int PORT = 6379;
    JedisPoolConfig config = new JedisPoolConfig();
    private JedisPool pool = new JedisPool(config, HOST, PORT);

    /**
     * 普通缓存获取
     * @param key 键
     * @return 值
     */
    public String get(String key) {
        Jedis jedis = pool.getResource();
        jedis.select(1);
        return key == null ? null : jedis.get(key);
    }

    /**
     * 普通缓存放入
     * @param key 键
     * @param value 值
     * @return true成功 false失败
     */
    public boolean set(String key, String value) {
        Jedis jedis = pool.getResource();
        jedis.select(1);
        try {
            jedis.set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 设置value失效时间
     * @param key 键
     * @param time 值
     * @return true成功 false失败
     */
    public boolean expire(String key, int time) {
        Jedis jedis = pool.getResource();
        jedis.select(1);
        try {
            jedis.expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * String转JSON
     * @param str 键
     */
    public JSONObject stringToJson(String str){
        JSONObject json = (JSONObject) JSONObject.parse(str);
        return json;
    }

    /**
     * JSON转String
     * @param json 键
     */
    public String jsonToString(JSONObject json){
        String str = json.toJSONString();
        return str;
    }

    /**
     * 从cookie获取salt
     * @param cookies
     * @return
     */
    public String getSalt(Cookie[] cookies){
        String salt = "";
        if(cookies == null){
            return salt;
        }
        for(Cookie cookie : cookies){
            if("salt".equals(cookie.getName())){
                salt = cookie.getValue();
            }
        }
        return salt;
    }

    /**
     * 每次请求重设cookie过期时间
     */
    public Cookie resetCookie(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        String salt = getSalt(cookies);

        expire(salt,30*60);

        Cookie userCookie = new Cookie("salt", salt);
        userCookie.setMaxAge(30*60);
        userCookie.setPath("/");
        return userCookie;
    }

}